package com.jiaquyun.jcps.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ToastUtils
import com.jiaquyun.jcps.R
import io.reactivex.disposables.CompositeDisposable

abstract class BaseAbstractFragment : Fragment(), View.OnTouchListener {

    val dispose: CompositeDisposable = CompositeDisposable()

    private var isFirstLoad = false

    /**
     * 需要绑定的视图ID
     */
    abstract val layoutResId: Int

    private var rootView: View? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return rootView ?: inflater.inflate(layoutResId, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.setOnTouchListener(this)
        doBeforeInit()
        initView()
    }

    override fun onResume() {
        super.onResume()
        if (!isFirstLoad) {
            initData()
            isFirstLoad = true
        } else {
            onRefreshLoad()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        dispose.clear()
    }

    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        return true
    }

    /**
     * 设置沉浸式状态栏
     * */
    private fun initStatusBar() {
        //设置状态栏模式
        BarUtils.setStatusBarLightMode(
            requireActivity(), (true)
        )
        //设置状态栏颜色
        BarUtils.setStatusBarColor(
            requireActivity(), (0x00000000)
        )
        //为标题栏添加状态栏的高度
        stateBar()?.let {
            BarUtils.addMarginTopEqualStatusBarHeight(it)
        }
    }


    /**
     * 在初始化视图之前的操作
     */
    open fun doBeforeInit() = Unit

    /**
     * 初始化UI
     */
    open fun initView() = Unit

    /**
     * 初始化数据
     */
    open fun initData() = Unit


    /**
     * 刷新数据
     */
    open fun onRefreshLoad() = Unit

    /**
     *
     * */
    open fun stateBar(): View? = null

    /**
     * toast提示
     * */
    fun toast(message: String) {
        ToastUtils.showShort(message)
    }

    /**
     * 创建加载布局
     * */
    fun createLoadingView(): View =
        layoutInflater.inflate(R.layout.view_empty_load, null)

    /**
     * 创建null布局
     * */
    fun createEmptyNullView(message: String? = null): View =
        layoutInflater.inflate(R.layout.view_empty_null, null).apply {
            message?.let {
                findViewById<TextView>(R.id.tvNullMessage).text = it
            }
        }

}